<template>
  <div class="cart-page">
    <!-- 顶部导航 -->
    <div class="cart-header">
      <el-button type="text" @click="$router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2 class="page-title">购物车</h2>
      <el-button type="text" class="edit-btn" @click="toggleEditMode">
        {{ isEditMode ? '完成' : '编辑' }}
      </el-button>
    </div>

    <!-- 商品列表 -->
    <div class="cart-items">
      <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
        <div class="item-checkbox">
          <el-checkbox v-model="item.selected" @change="updateTotal"></el-checkbox>
        </div>
        <div class="item-content">
          <img :src="item.image" alt="商品图片" class="item-image">
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-spec">{{ item.spec }}&nbsp;&nbsp;x{{ item.quantity }}</div>
            <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
            <div class="item-actions">
              <div v-if="isEditMode" class="quantity-editor">
                <el-button type="text" @click="decreaseQuantity(index)">
                  <el-icon><Minus /></el-icon>
                </el-button>
                <span class="quantity-value">{{ item.quantity }}</span>
                <el-button type="text" @click="increaseQuantity(index)">
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
              <el-button v-if="isEditMode" type="text" class="delete-btn" @click="removeItem(index)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="cart-footer">
      <div class="select-all">
        <el-checkbox v-model="selectAll" @change="toggleSelectAll"></el-checkbox>
        <span>全选</span>
      </div>
      <div class="total-price" v-if="!isEditMode">
        合计：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <el-button 
        :type="selectedCount > 0 ? 'primary' : 'default'" 
        class="checkout-btn"
        :disabled="selectedCount === 0"
        @click="checkout"
      >
        {{ isEditMode ? '删除所选' : '结算' }}({{ selectedCount }})
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Minus, Plus, Delete } from '@element-plus/icons-vue'
import { ElButton, ElIcon, ElCheckbox } from 'element-plus'

const router = useRouter()


// 购物车数据
const cartItems = ref([
  {
    id: 1,
    name: '捆绑打包编织不易断绳子',
    spec: '蓝色/20米',
    price: 88.00,
    quantity: 1,
    image: 'https://picsum.photos/300/300?random=1',
    selected: true
  },
  {
    id: 2,
    name: '高强度尼龙绳',
    spec: '黑色/30米',
    price: 120.00,
    quantity: 2,
    image: 'https://picsum.photos/300/300?random=2',
    selected: true
  },
  {
    id: 3,
    name: '轻质耐磨登山绳',
    spec: '红色/15米',
    price: 99.00,
    quantity: 1,
    image: 'https://picsum.photos/300/300?random=3',
    selected: false
  }
])

// 编辑模式
const isEditMode = ref(false)

// 全选状态
const selectAll = ref(true)

// 计算选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return item.selected ? total + (item.price * item.quantity) : total
  }, 0)
})

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
}

// 更新总价
const updateTotal = () => {
  // 当有商品未选中时，取消全选状态
  const allSelected = cartItems.value.every(item => item.selected)
  selectAll.value = allSelected
}

// 全选/取消全选
const toggleSelectAll = (value) => {
  cartItems.value.forEach(item => {
    item.selected = value
  })
}

// 减少数量
// 减少数量时同步更新localStorage
const decreaseQuantity = (index) => {
  if (cartItems.value[index].quantity > 1) {
    cartItems.value[index].quantity--
    localStorage.setItem('cartItems', JSON.stringify(cartItems.value));
  }
}

// 增加数量// 增加数量时同步更新localStorage
const increaseQuantity = (index) => {
  cartItems.value[index].quantity++
  localStorage.setItem('cartItems', JSON.stringify(cartItems.value));
  console.log("商品数量",cartItems.value[index].quantity)
  
}

// 删除商品
const removeItem = (index) => {
  // 1. 从数组中删除商品
  cartItems.value.splice(index, 1);
  // 2. 更新全选状态和总价
  updateTotal();
  // 3. 将最新的购物车数据存入localStorage
  localStorage.setItem('cartItems', JSON.stringify(cartItems.value));
};

// 结算
const checkout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  
  if (selectedItems.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  
//   const cartItems = ref([
//     { productId: '1', spec: 'spec1', quantity: 2, addressId: 'addr1', price: 10 },
//     { productId: '2', spec: 'spec2', quantity: 1, addressId: 'addr2', price: 15 }
// ]);
// const encodedCartItems = encodeURIComponent(JSON.stringify(cartItems));
// router.push({
//     name: 'Checkout',
//     query: { cartItems: encodedCartItems }
// });
 // 在实际项目中，这里可能会跳转到结算页面或提交订单
  console.log('结算商品:', selectedItems)
  // 模拟跳转到结算页面，携带第一个选中商品的信息
  // const firstItem = selectedItems[0]
  const encodedCartItems = encodeURIComponent(JSON.stringify(selectedItems));
router.push({
    name: 'Checkout',
    query: { cartItems: encodedCartItems }
})
   
  // router.push({
  //   name: 'Checkout',
  //   params: {
  //     productId: firstItem.id,
  //     spec: firstItem.spec,
  //     quantity: firstItem.quantity,
  //     addressId: 0 // 默认地址ID
  //   }
  // })
}

onMounted(() => {
  // 从localStorage加载购物车数据（如果有）
  const savedCart = localStorage.getItem('cartItems')
  if (savedCart) {
    cartItems.value = JSON.parse(savedCart)
  }
  updateTotal()
})
</script>

<style scoped>
.cart-page {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 顶部导航 */
.cart-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 15px;
  background-color: red;
  color: white;
  border-radius: 8px;
}

.back-btn, .edit-btn {
  color: white;
  padding: 0 15px;
}

.page-title {
  flex: 1;
  text-align: center;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 商品列表 */
.cart-items {
  margin-bottom: 80px;
}

.cart-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.item-checkbox {
  margin-right: 10px;
}

.item-content {
  display: flex;
  flex: 1;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 15px;
  margin-bottom: 5px;
  line-height: 1.4;
}

.item-spec {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.item-price {
  color: #ff4d4f;
  font-weight: 600;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.quantity-editor {
  display: flex;
  align-items: center;
}

.quantity-value {
  width: 30px;
  text-align: center;
}

.delete-btn {
  color: #ff4d4f;
}

/* 底部结算栏 */
.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.select-all {
  display: flex;
  align-items: center;
}

.total-price {
  flex: 1;
  text-align: right;
  margin-right: 15px;
  font-size: 16px;
}

.price {
  color: #ff4d4f;
  font-weight: 600;
}

.checkout-btn {
  width: 120px;
  height: 40px;
  border-radius: 20px;
  font-size: 16px;
}
</style>